// 餐品分类控制器
import FoodCategory from './FoodCategoryModel.js';
import { asyncHandler, ApiError } from '../../middleware/errorHandler.js';

export const FoodCategoryController = {
    /**
     * 创建餐品分类
     */
    create: asyncHandler(async (req, res) => {
        const { name, description, status, sort_order } = req.body;
        
        if (!name) {
            throw ApiError.badRequest('分类名称不能为空');
        }
        
        // 检查分类名称是否已存在
        const existingCategory = await FoodCategory.findOne({ where: { name } });
        if (existingCategory) {
            throw ApiError.conflict('分类名称已存在');
        }
        
        const category = await FoodCategory.create({
            name,
            description,
            status,
            sort_order
        });
        
        return res.status(201).json({
            success: true,
            message: '分类创建成功',
            data: category
        });
    }),

    /**
     * 获取所有餐品分类
     */
    getAll: asyncHandler(async (req, res) => {
        const categories = await FoodCategory.findAll({
            order: [['sort_order', 'ASC'], ['id', 'ASC']]
        });
        
        return res.json({
            success: true,
            data: categories
        });
    }),

    /**
     * 获取单个餐品分类
     */
    getOne: asyncHandler(async (req, res) => {
        const { id } = req.params;
        
        const category = await FoodCategory.findByPk(id);
        if (!category) {
            throw ApiError.notFound('分类不存在');
        }
        
        return res.json({
            success: true,
            data: category
        });
    }),

    /**
     * 更新餐品分类
     */
    update: asyncHandler(async (req, res) => {
        const { id } = req.params;
        const { name, description, status, sort_order } = req.body;
        
        const category = await FoodCategory.findByPk(id);
        if (!category) {
            throw ApiError.notFound('分类不存在');
        }
        
        // 如果要更新名称，检查新名称是否与其他分类重复
        if (name && name !== category.name) {
            const existingCategory = await FoodCategory.findOne({
                where: { name }
            });
            if (existingCategory) {
                throw ApiError.conflict('分类名称已存在');
            }
        }
        
        await category.update({
            name: name || category.name,
            description: description !== undefined ? description : category.description,
            status: status || category.status,
            sort_order: sort_order !== undefined ? sort_order : category.sort_order
        });
        
        return res.json({
            success: true,
            message: '分类更新成功',
            data: category
        });
    }),

    /**
     * 删除餐品分类
     */
    delete: asyncHandler(async (req, res) => {
        const { id } = req.params;
        
        const category = await FoodCategory.findByPk(id);
        if (!category) {
            throw ApiError.notFound('分类不存在');
        }
        
        // 检查分类下是否有餐品
        const foodCount = await category.countFoods();
        if (foodCount > 0) {
            throw ApiError.badRequest('该分类下存在餐品，无法删除');
        }
        
        await category.destroy();
        
        return res.json({
            success: true,
            message: '分类删除成功'
        });
    })
};